package com.qibao.toolkit.exception.handler;

import com.qibao.toolkit.exception.strategy.ExceptionHandleStrategy;
import com.qibao.toolkit.exception.strategy.factory.ExceptionHandleStrategyHolder;
import com.qibao.toolkit.web.ResponseModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 提供对异常的全局处理
 *
 * @author wangcheng
 * @version $Id: GlobalExceptionHandler.java, v0.1 2018/9/26 10:04 wangcheng Exp $$
 */
public class GlobalExceptionHandler  implements ApplicationContextAware {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    public static final String DEFAULT_GLOBAL_EXCEPTION_HANDLE_BEAN_NAME = "globalExceptionHandler";

    private ExceptionHandleStrategyHolder strategyHolder;


    @ExceptionHandler(Throwable.class)
    public ResponseModel handleException(HttpServletRequest request, HttpServletResponse response, Throwable e) {
        logger.info("处理异常：" + e.getClass().getName());
        ExceptionHandleStrategy strategy = strategyHolder.getStrategyByThrowable(e);
        logger.info("获取策略：{}", strategy.getClass().getName());
        return strategy.handle(request, response, e);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.strategyHolder = applicationContext
                .getBean(ExceptionHandleStrategyHolder.class);
    }
}
